package com.presto.directo.utils

import android.content.Context
import android.content.pm.ApplicationInfo
import com.presto.directo.entity.AppInfoEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object AppListUtil {

    suspend fun getAppList(context: Context): List<AppInfoEntity> {
        return withContext(Dispatchers.IO) {
            val apps = arrayListOf<AppInfoEntity>()
            val allApps = context.packageManager.getInstalledPackages(0)
            if (!allApps.isNullOrEmpty()) {
                allApps.forEach {
                    try {
                        if (it.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM <= 0) {
                            val appEntity = AppInfoEntity()
                            appEntity.appLabel = it.applicationInfo.loadLabel(context.packageManager).toString()
                            appEntity.packageName = it.packageName ?: ""
                            appEntity.versionName = it.versionName ?: ""
                            appEntity.versionCode = it.versionCode
                            appEntity.firstInstallTime = it.firstInstallTime.toString()
                            appEntity.lastUpdateTime = it.lastUpdateTime.toString()
                            appEntity.type = if ((it.firstInstallTime % 100).toInt() != 0) 1 else 0
                            apps.add(appEntity)
                        }
                    } catch (e: Exception) {
                    }
                }
            }
            apps
        }

    }

}